package cn.school.demo.ui.forget_password

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import cn.school.demo.pojo.Result
import cn.school.demo.repository.DataRepository
import cn.school.demo.repository.ForgetPasswordRepository
import cn.school.demo.util.StringUtil

class ForgetPasswordViewModel : ViewModel() {

    private lateinit var _result: LiveData<Result>
    val result: LiveData<Result> get() = _result

    private lateinit var _getCode: LiveData<String>
    val getCode: LiveData<String> get() = _getCode

    private val _id = MutableLiveData<String>()
    val id: LiveData<String> get() = _id

    private val _phone = MutableLiveData<String>()
    val phone: LiveData<String> get() = _phone

    private val _pwd = MutableLiveData<String>()
    val pwd: LiveData<String> get() = _pwd

    private val _rePwd = MutableLiveData<String>()
    val rePwd: LiveData<String> get() = _rePwd

    private val _code = MutableLiveData<String>()
    val code: LiveData<String> get() = _code

    init {
        _id.value = ""
        _phone.value = ""
        _pwd.value = ""
        _rePwd.value = ""
        _code.value = ""
    }

    fun getResult() {
        _result = ForgetPasswordRepository().userDetection(_id.value!!, _phone.value!!)
    }

    fun getCodeText(phone: String){
        _getCode = DataRepository().getCode(phone)
    }

    fun resetPwd() {
        _result = ForgetPasswordRepository().resetPassword(
            mapOf(
                "sfNumber" to _id.value!!.toInt(),
                "password" to _pwd.value!!,
            )
        )
    }

    fun setId(id: String) {
        _id.value = id
    }

    fun setPhone(phone: String) {
        _phone.value = phone
    }

    fun setPwd(pwd: String) {
        _pwd.value = pwd
    }

    fun setRePwd(pwd: String) {
        _rePwd.value = pwd
    }

    fun setCode(code: String) {
        _code.value = code
    }

    fun dataDetection() = when {
        _id.value!!.isEmpty() -> "请输入学（工）号."
        _phone.value!!.isEmpty() -> "请输入手机号."
        !StringUtil.isStudentID(_id.value!!) -> "学（工）号输入有误."
        _id.value!!.length > 10 -> "学工号长度超限."
        !StringUtil.isMobilePhone(_phone.value!!) -> "手机号格式不对！"
        else -> null
    }

    fun dataDetectionBySecond() = when {
        _pwd.value!!.isEmpty() -> "请输入新密码！"
        !StringUtil.isPassword(_pwd.value!!) -> "新密码输入有误！"
        _pwd.value!!.length > 16 -> "新密码长度超限！"
        _rePwd.value!!.isEmpty() -> "请再次输入新密码！"
        !StringUtil.isPassword(_rePwd.value!!) -> "再次输入的密码有误！"
        _rePwd.value!!.length > 16 -> "再次输入的密码长度超限！"
        _pwd.value != _rePwd.value -> "两次密码不一致！"
        _code.value!!.isEmpty() -> "请输入验证码！"
        else -> null
    }
}